<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        let arr = [
            { id: 0, name: '1', parent: -1, childNode: [] },
            { id: 1, name: '1', parent: 0, childNode: [] },
            { id: 99, name: '1-1', parent: 1, childNode: [] },
            { id: 111, name: '1-1-1', parent: 99, childNode: [] },
            { id: 66, name: '1-1-2', parent: 99, childNode: [] },
            { id: 1121, name: '1-1-2-1', parent: 112, childNode: [] },
            { id: 12, name: '1-2', parent: 1, childNode: [] },
            { id: 2, name: '2', parent: 0, childNode: [] },
            { id: 21, name: '2-1', parent: 2, childNode: [] },
            { id: 22, name: '2-2', parent: 2, childNode: [] },
            { id: 221, name: '2-2-1', parent: 22, childNode: [] },
            { id: 3, name: '3', parent: 0, childNode: [] },
            { id: 31, name: '3-1', parent: 3, childNode: [] },
            { id: 32, name: '3-2', parent: 3, childNode: [] }
        ]

        function arrToTree(arr, parentId) {
            // 判断是否是顶层节点，如果是就返回。不是的话就判断是不是⾃⼰要找的⼦节点
            const filterArr = arr.filter(item => {
                console.log('parentId',parentId)
                return parentId === undefined ? item.parent === -1 : item.parent === parentId
            })
            console.log('filterArr',filterArr)
            // 进⾏递归调⽤把⼦节点加到⽗节点的 childNode⾥⾯去
            filterArr.map(item => {
                item.childNode = arrToTree(arr, item.id)
                    return item
            })
            return filterArr
        }
    let tree2 = arrToTree(arr)
    console.log('tree2',tree2);
    
    </script>
</body>
</html>